package com.ioc;

import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import com.conf.CommonConfig;
import ejp.DatabaseManager;

/**
 * @author xied
 *
 */
@SuppressWarnings("static-access")
public class DatabaseManagerFactory {
	private static String dburl;
	private static String dbdriver;
	private static String dbuser;
	private static String dbpwd;
	private static String dbname;
	private static int poolsize;
	private static DataSource datasource;
	private static DatabaseManager dbm = null;
	private static int initialSize=0,maxActive=0,maxIdle=0;

	
	static{
		try{
			dbuser = CommonConfig.getParamete("mysql.username");
			dbdriver = CommonConfig.getParamete("mysql.driver");
			dburl = CommonConfig.getParamete("mysql.url");
			dbpwd = CommonConfig.getParamete("mysql.password");
			dbname = CommonConfig.getParamete("mysql.dbname");
			initialSize = Integer.parseInt(CommonConfig.getParamete("initialSize"));
			maxActive = Integer.parseInt(CommonConfig.getParamete("maxActive"));
			poolsize =  maxIdle = Integer.parseInt(CommonConfig.getParamete("maxIdle"));
			
//			dbm =  new DatabaseManager(dbname,poolsize,dbdriver,dburl,dbuser,dbpwd);
			datasource = setupDataSource(dbdriver, dbuser, dbpwd, dburl,initialSize,maxActive,maxIdle);
			dbm =  new DatabaseManager(dbname,poolsize, datasource);
//			dbm.setLogLevel(Level.OFF);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	static public DatabaseManager getDatabaseManager() {
		return dbm;
	}

	
	/**
	 * 取数据源
	 * @param jdbcdriver
	 * @param username
	 * @param pwd
	 * @param connectURI
	 * @param initialSize
	 * @param maxActive
	 * @param maxIdle
	 * @return DataSource
	 */
	private static DataSource setupDataSource(String jdbcdriver,String username,String pwd,String connectURI,int initialSize,int maxActive,int maxIdle) {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(jdbcdriver);
        ds.setUsername(username);
        ds.setPassword(pwd);
        ds.setUrl(connectURI);
        ds.setInitialSize(initialSize);
        ds.setMaxActive(maxActive);
        ds.setMaxIdle(maxIdle);
        return ds;
    }
	
	
	
}
